using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Demo.Db;
using Demo.Models;

namespace Demo.Repository
{
    public class EfRepository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly DemoDb _db;
        private readonly DbSet<T> _table;

        public IQueryable<T> Table
        {
            get
            {
                return _table as IQueryable<T>;
            }
        }
          public void Insert(T entity)
        {
            entity.IsActived = true;
            entity.IsDeleted = false;
            entity.CreatedTime = DateTime.Now;
            entity.UpdatedTime = DateTime.Now;
            entity.DisplayOrder = 0;
            _table.Add(entity);
            _db.SaveChanges();
        }

        public EfRepository()
        {
            _db = new DemoDb();
            _table = _db.Set<T>();
        }
        public T GetById(int id)
        {
            var entity = _table.Where(x => x.IsDeleted == false && x.Id == id).FirstOrDefault();
            return entity;
        }
        public void Delete(int id)
        {
            var entity = _table.Where(x => x.Id == id).FirstOrDefault();
            entity.IsDeleted=true;
            entity.UpdatedTime=DateTime.Now;

            _table.Update(entity);
            _db.SaveChanges();
        }

      

        public void Update(T entity)
        {
            entity.UpdatedTime = DateTime.Now;

            _table.Update(entity);
            _db.SaveChanges();
        }

        
    }
}